const api = require('./utils/request')
// app.js
App({
  onLaunch() {
    // 展示本地存储能力
    const logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)
  },
  globalData: {
    userInfo: null,
    isLogin: false
  },
  appAuthCheck() {
    console.log('开始登录')
    const that = this
    return new Promise((resolve, reject) => {
      // 登录
      wx.login({
        success: res => {
        console.log("👨🏻‍💻 ~ res", res)
          if(res.code) {
            const data = {
              code: res.code
            }
            api.post('/user/login', data)
              .then(res => {
              console.log("👨🏻‍💻 ~ res", res)
                if(res.code === '0') {
                  const { session_id } = res.data;
                  wx.setStorageSync('session_id', session_id);
                  that.getUserInfo(session_id, resolve, reject);
                }
              })
          }
        }
      })
    })
  },
  getUserInfo(session_id, resolve, reject) {
    api.get('/user/userinfo', {session_id}).then((res) => {
      if (res.code === '0') {
        const { hasAuth,  is_super_user} = res.data;
        wx.setStorageSync('hasAuth', hasAuth);
        wx.setStorageSync('is_super_user', is_super_user);
        if (!hasAuth) {
          wx.navigateTo({
            url: '/pages/login/login',
          })
          reject()
        } else {
          resolve()
        }
      }
    })
  }
})
